<?php
namespace App\Service\Item\Fxotary\Admin;

use App\Service\Item\Fxotary\BaseService as Service;
use Illuminate\Support\Facades\DB;

class AdminService extends Service
{
    //管理员

    //列表
    public function getIndex($token)
    {
        $uid = $this->uidByToken($token);
        $db = $this->dbConn($this->xmUser)
            ->select('id', 'nick')
            ->where('type', 2)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有菜单', 'data' => []);
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total);
    }

    //一个
    public function getOne($token, $id)
    {
        $uid = $this->uidByToken($token);
        $res = (array) $this->dbConn($this->xmUser)
            ->select('id', 'nick', 'passwd')
            ->where('uid', $uid)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '没有管理员');
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res);
    }

    /**
     * 修改
     * @param int $id
     * @param string $title
     */
    public function modify($id, $title)
    {
        $res = (array) $this->dbConn($this->xmUser)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '记录不存在');
        }
        $adminData = [
            'nick' => $title,
            'uptime' => toDate(),
        ];
        $up = $this->dbConn($this->xmUser)->where('id', $id)->update($adminData);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 密码更新
     * @param int $id
     * @param string $pwd
     * @param string $pwd2
     */
    public function setPwd($id, $pwd, $pwd2)
    {
        $res = (array) $this->dbConn($this->xmUser)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '没有管理员');
        }
        if ($res['passwd'] != md5($pwd)) {
            return array('code' => -2, 'msg' => '密码错误');
        }
        $adminData = [
            'passwd' => md5($pwd2),
            'uptime' => toDate(),
        ];
        $up = $this->dbConn($this->xmUser)->where('id', $id)->update($adminData);
        if (!$up) {
            return array('code' => -2, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }
}